import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { MdlDialogService } from '@angular-mdl/core';
import { finalize, tap } from 'rxjs/operators';

@Injectable()
export class ErrorResponseInterceptor implements HttpInterceptor {

    constructor(
        private dialogService: MdlDialogService) { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const started = Date.now();
        let ok = true;
        let code: number;
        let msg: string;

        return next.handle(req)
            .pipe(
                tap(
                    // Succeeds when there is a response; ignore other events
                    event => ok = true,
                    // Operation failed; error is an HttpErrorResponse
                    error => {
                        ok = false;
                        code = error.error.code;
                        msg = error.error.message;
                    }
                ),
                // Log when response observable either completes or errors
                finalize(() => {
                    if (!ok) {
                        this.dialogService.alert(msg || "系统异常，请联系管理员", '确定');
                    }
                })
            );
    }
}